"""
Macros module allow to transform extended python to standard python code
Input example:
#include <header.h>

<?
    for v in vars:
        >> var = $v;
        if v.type != None:
            >> type = $(v.type)
?>

Output:
print("#include <header.h>")
print("")
for v in vars:
    print("var = " + str(v) + ";")
    if v.type != None:
        print("type = " + str(v.type))
"""

from S3D.PYD.Macros import *

__all__ = ["Macros", "fromFile", "fromString"]

def fromFile(filename, processAsPython = False):
    with open(filename, "r") as f:
        text = f.read()
        return Macros(text, processAsPython)

def fromString(text, processAsPython = False):
    return Macros(text, processAsPython)

class MacrosStdWriter:
    def __init__(self):
        self.text = ""
    def __call__(self, text):
        self.text += text

def MacrosCall(self, locals = None, globals = None):
    if globals == None:
        globals = __builtins__
    if locals == None:
        locals = {}

    writer = None
    if Macros.OutputMethod not in globals.keys() and Macros.OutputMethod not in locals.keys():
        writer = MacrosStdWriter()
        locals[Macros.OutputMethod] = writer

    exec(self.code, globals, locals)
    if writer != None:
        del locals[Macros.OutputMethod]
        return writer.text.rstrip()

Macros.fromFile = fromFile
Macros.fromString = fromString
Macros.__call__ = MacrosCall